import $ from 'jquery'


export default ({
    state: {
        id:"",
        username:"",
        photo:"",
        token:"",
        is_login:false, ///一开始未登录
        pulling_info:true,
    },

    getters: {
    },

    mutations: {
        updateUser(state,student){
            state.id=student.id;
            state.username=student.username;
            state.photo=student.photo;
            state.is_login=student.is_login;
        },
      
        updateToken(state,token){
           state.token=token;
        },

        logout(state){
            state.id="";
            state.username="";
            state.photo="";
            state.token="";
            state.is_login=false;
        },
        
        updatePullingInfo(state,pulling_info)
        {
            state.pulling_info=pulling_info;
        },
      
    },

    actions: {
        login(context,data){
          $.ajax({
            url:"http://127.0.0.1:3000/user/account/token/",
            type:"post",
            data:{
              username:data.username,
              password:data.password,
            },
            success(resp){
                if(resp.error_massage ==="success")
                {
                    localStorage.setItem("jwt_token",resp.token);
                    context.commit("updateToken",resp.token);
                   //  data.success(resp);
                }
                else{
               //  data.error(resp);
                }
            },
            error(){
             // data.error(resp);
            }
          });
        },

        getinfo(context,data){
            $.ajax({
                url:"http://localhost:3000/user/account/info/",
                type:"get",
                headers:{
                    Authorization:"Bearer "+ context.state.token,
                },
                    success(resp){
                        if(resp.error_massage==="success")
                        {
                            context.commit("updateUser",{
                                ...resp,
                                is_login:true,
                            });
                            data.success(resp);
                        }
                        else {
                            data.error(resp);
                        }
                    },
                    error(resp)
                    {
                        data.error(resp);
                    }
                  });
                },

                logout(context)
                {
                    localStorage.removeItem("jwt_token");
                    context.commit("logout");
                    
                },
                submitInfo(context)
                {
       
                  context.commit("submitInfo");
     
                }           
    },
    modules: {
       
    }
  
})